//
//  FileManagerViewModel.swift
//  MyCloset
//
//  Created by 牟好好 on 2024/10/27.
//

import SwiftUI

class FileManagerViewModel: ObservableObject {
    // 获取到的图片
    @Published var image: UIImage? = nil
    let manager = LocalFileManager.instance
    // 告知用户是否保存或删除成功
    @Published var infoMessage: String = ""
    // 缓存目录大小
    @Published var tempDirectorySize: String = "0 MB"
    
    // 返回保存路径给CoreData
    func saveImage(image: UIImage, id: UUID, completion: @escaping (String) -> Void) {
        // 保存图片到 FileManager
        let (message, path) = manager.saveImage(image: image, id: id)
        infoMessage = message
        
        guard let path = path else { return }
        // 传递路径供CoreData存储
        completion(path)
    }
    
    
    func deleteImage(id: UUID) {
        infoMessage = manager.deleteImage(id: id)
    }
    
    func getImageFromFileManager(id: UUID) -> UIImage? {
        return manager.getImage(id: id)
    }
    
    func deleteTempFolder() {
        manager.deleteTempFolder()
        calculateTempDirectorySize()
    }
    
    // 计算临时目录的大小
    func calculateTempDirectorySize() {
        let tempDirectory = FileManager.default.temporaryDirectory
        var totalSize: UInt64 = 0
        
        do {
            let files = try FileManager.default.contentsOfDirectory(at: tempDirectory, includingPropertiesForKeys: [.fileSizeKey], options: .skipsHiddenFiles)
            
            for file in files {
                let fileAttributes = try FileManager.default.attributesOfItem(atPath: file.path)
                if let fileSize = fileAttributes[FileAttributeKey.size] as? UInt64 {
                    totalSize += fileSize
                }
            }
            
            // 更新 tempDirectorySize 为可显示的格式（MB）
            DispatchQueue.main.async {
                if totalSize == 0 {
                    self.tempDirectorySize = "0 MB"
                } else {
                    self.tempDirectorySize = String(format: "%.2f MB", Double(totalSize) / (1024.0 * 1024.0))
                }
            }
        } catch {
            print("计算临时目录缓存出错: \(error.localizedDescription)")
        }
    }
}

